package dp.mobile.game;

import java.util.ArrayList;

import dp.mobile.glwrapper.GLTexture;
import dp.mobile.glwrapper.GLTiledTexture;
import dp.mobile.glwrapper.GameRenderer;
import dp.mobile.system.Utilities;

public class Tileset {
	private static final String TAG = "Tileset";
	
	public Tileset(String image, String offlineNodeImage, String onlineNodeImage, String buildables) {
        //Create with default column
		this(image, offlineNodeImage, onlineNodeImage, Utilities.TILESET_COLUMN, buildables);
	}

	public Tileset(String image, String offlineNodeImage, String onlineNodeImage, int column, String buildables) {
		//Create tiles
		//Create image
		mOfflineNodeImages 	= new ArrayList<GLTexture>();
		mOnlineNodeImages	= new ArrayList<GLTexture>();
		mOfflineNodeImage 	= GameRenderer.instance().allocateTexture(offlineNodeImage);
		mOnlineNodeImage 	= GameRenderer.instance().allocateTexture(onlineNodeImage);
		
		mOfflineNodeImages.add(mOfflineNodeImage);
		mOnlineNodeImages.add(mOnlineNodeImage);
		
		GLTexture mainTexture = GameRenderer.instance().allocateTexture(image, true);
		final int row 	= mainTexture.Height / Utilities.TILE_HEIGHT;
		mImages			= new GLTiledTexture[column * row];
		
		//Slice it
		for (int y = 0; y < row ; y ++) {
			for (int x = 0; x < column; x++) {
				final float left 	= (float)x 		/ (float)column;
				final float right 	= (float)(x + 1)/ (float)column;
				final float top		= (float)y 		/ (float)row;
				final float bottom	= (float)(y + 1)/ (float)row;
				
				float[] crop = new float[] {
					left,	bottom,
					right,	bottom,
					left,	top,
					right,	top
				};
				mImages[(y * column) + x] = new GLTiledTexture(mainTexture, crop);
			}
		}

         //Parse buildable
        String[] buildable = buildables.split(";");
        mIsBuildable = new boolean[buildable.length];

        for(int i = 0; i < buildable.length; ++i) mIsBuildable[i] = buildable[i].trim().equals("1");
	}
	
	public GLTiledTexture getTile(int index) {
		return mImages[index];
	}

    public boolean isTileBuildable(int index){
        return mIsBuildable[index];
    }
    
    public GLTexture getOfflineNodeImage() {
    	return mOfflineNodeImage;
    }
    
    public GLTexture getOfflineNodeImage(int index) {
    	if (mOfflineNodeImages.size() > index)
    		return mOfflineNodeImages.get(index);
    	else
    		return null;
    }
    
    public GLTexture getOnlineNodeImage() {
    	return mOnlineNodeImage;
    }
    
    public GLTexture getOnlineNodeImage(int index) {
    	if (mOnlineNodeImages.size() > index)
    		return mOnlineNodeImages.get(index);
    	else
    		return null;
    }
	
    protected GLTexture			mOfflineNodeImage, mOnlineNodeImage;
    protected ArrayList<GLTexture> mOfflineNodeImages, mOnlineNodeImages;
	protected GLTiledTexture[]	mImages;
    protected boolean[] 		mIsBuildable;
}
